package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

    @Autowired
    private LiveRoomMapper liveRoomMapper;

    @Override
    public LiveRoom getCurrentLive(Long userId) {
        LambdaQueryWrapper<LiveRoom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LiveRoom::getUserId, userId);
        lambdaQueryWrapper.ge(LiveRoom::getExpireTime, new Date());
        LiveRoom liveRoom = liveRoomMapper.selectOne(lambdaQueryWrapper);
        return liveRoom;
    }
    /**
     * @description: 创建直播
     * @author Petrichor
     * @date 2024/1/12 21:22
     * @param liveRoomVo 直播间信息
     * @return liveRoom
     **/
    @Override
    public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo, Long userId) {
        long count = liveRoomMapper.selectCount(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId, userId).gt(LiveRoom::getExpireTime, new Date()));
        if(count > 0) {
            throw new GuiguException(ResultCodeEnum.EXIST_NO_EXPIRE_LIVE);
        }

        // 创建直播间对象
        LiveRoom liveRoom = new LiveRoom();
        BeanUtils.copyProperties(liveRoomVo, liveRoom);
        liveRoom.setUserId(userId);
        liveRoom.setAppName("live");
        liveRoom.setStreamName("guigu"+userId);
        long txTime = liveRoom.getExpireTime().getTime() / 1000;
        TencentLiveAddressVo addressUrl = LiveAutoAddressUtil.getAddressUrl(liveRoom.getStreamName(), txTime);
        liveRoom.setPushUrl(addressUrl.getPushWebRtcUrl());
        liveRoom.setPlayUrl(addressUrl.getPullWebRtcUrl());

        // 保存直播间数据
        liveRoomMapper.insert(liveRoom);

        // 返回直播间信息
        return liveRoom;
    }
    /**
     * @description: 获取当前直播列表
     * @author Petrichor
     * @date 2024/1/12 21:26
     * @return 当前直播列表
     **/
    @Override
    public List<LiveRoom> findLiveList() {
        LambdaQueryWrapper<LiveRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(LiveRoom::getExpireTime, new Date());
        return liveRoomMapper.selectList(queryWrapper);
    }
}
